package com.etone.smartAudit.filter;

import com.etone.smartAudit.security.SecurityUtils;
import com.etone.smartAudit.security.jwt.JWTConfigurer;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Log4j2
@Component
public class TokenFilter extends GenericFilterBean {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public static String REDIS_TOKEN_KEY_PREFIX = "adminToken:";

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String currentUserLogin = SecurityUtils.getCurrentUserLogin();
        if (currentUserLogin != null && !"anonymousUser".equals(currentUserLogin)) {
            String key = TokenFilter.REDIS_TOKEN_KEY_PREFIX + currentUserLogin;
            Boolean hasToken = stringRedisTemplate.hasKey(key);
            if (hasToken!=null&&hasToken) {
                String curToken = stringRedisTemplate.opsForValue().get(key);
                String loginToken = ((HttpServletRequest) request).getHeader(JWTConfigurer.AUTHORIZATION_HEADER);
                if (!loginToken.equals(curToken)) {
                    logoutResponse(response);
                    return;
                }
            } else {
                logoutResponse(response);
                return;
            }

        }

        chain.doFilter(request, response);
    }

    private void logoutResponse(ServletResponse response) {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        httpServletResponse.setHeader("Force-Logout", "yes");
    }
}
